package com.ccccat.www.msgs;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
//import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ccccat.www.msgs.service.WakeLockService;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;

import java.util.*;

import android.os.*;
import android.app.*;
import android.content.*;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {


    public static String TAG = "SMSMANAGER";
    private Button btn_send, btn_improt, btn_send_more, socket_btn;
    private EditText phoneEt, contextEt, ms;
    private EasyRecyclerView rv_list;
    private ProgressDialog progressDialog;
    private List<Person> personList;
    private PersonAdapter mAdapter;
    private TextView tips;
    private RadioGroup rg_all;
    private int IDs = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }


    private void init() {
        personList = new ArrayList<>();
        mAdapter = new PersonAdapter();
        btn_send = (Button) this.findViewById(R.id.btn_send);
        tips = (TextView) this.findViewById(R.id.tips);
        btn_send_more = (Button) this.findViewById(R.id.btn_send_more);
        btn_improt = (Button) this.findViewById(R.id.btn_improt);
        socket_btn = (Button) this.findViewById(R.id.socket);
        phoneEt = (EditText) this.findViewById(R.id.phoneNumberEt);
        contextEt = (EditText) this.findViewById(R.id.contextEt);
        ms = (EditText) findViewById(R.id.ms);
        rg_all = (RadioGroup) this.findViewById(R.id.rg_all);
        rv_list = (EasyRecyclerView) this.findViewById(R.id.rv_list);
        progressDialog = new ProgressDialog(this);
        btn_send.setOnClickListener(this);
        btn_improt.setOnClickListener(this);
        btn_send_more.setOnClickListener(this);
        socket_btn.setOnClickListener(this);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        rv_list.setLayoutManager(mLayoutManager);
        rv_list.setItemAnimator(new DefaultItemAnimator());
        rv_list.setAdapter(mAdapter);
        rg_all.setOnCheckedChangeListener(this);
    }

    /**
     * 获取 excel 表格中的数据,不能在主线程中调用
     */
    private ArrayList<Person> getXlsData(String filePath, int index) {
        ArrayList<Person> persons = new ArrayList<>();
        try {
            InputStream is = new FileInputStream(filePath);
            Workbook workbook = Workbook.getWorkbook(is);
            Sheet sheet = workbook.getSheet(index);
            int sheetRows = sheet.getRows();
            for (int i = 0; i < sheetRows; i++) {
                Person person = new Person();
                person.setUserName(sheet.getCell(0, i).getContents());
                person.setPhoneNumber(sheet.getCell(1, i).getContents());
                person.setMsgContent(sheet.getCell(2, i).getContents());
                persons.add(person);
            }
            workbook.close();
        } catch (Exception e) {
            Log.d(TAG, "数据读取错误=" + e);
        }
        return persons;
    }

    //  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 导入Excel表格
            case R.id.btn_improt:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
                break;
            // 发送
            case R.id.btn_send:
                String phones = phoneEt.getText().toString().trim();
                String contexts = contextEt.getText().toString().trim();

                int timea = 1;
                try {
                    timea = Integer.parseInt(ms.getText().toString());
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "输入的时间出现异常", Toast.LENGTH_SHORT);
                    return;
                }
                if (TextUtils.isEmpty(phones) || TextUtils.isEmpty(contexts)) {
                    Toast.makeText(MainActivity.this, "号码或内容不能为空！", Toast.LENGTH_SHORT);
                    return;
                }
                String[] phonea = phones.split("\n");
                String[] contexta = contexts.split("\n");
                asyMs(phonea, contexta, timea);
                Toast.makeText(getApplicationContext(), "发送开始了", Toast.LENGTH_SHORT).show();
                break;
            // 批量发送
            case R.id.btn_send_more:
                int times = 1;
                try {
                    times = Integer.parseInt(ms.getText().toString());
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "输入的时间出现异常", Toast.LENGTH_SHORT);
                    return;
                }

                asyMsExcel(personList, times);
                break;
            case R.id.socket:

                asyMsg();
                CreateUserDialog createUserDialog = new CreateUserDialog(this);
                createUserDialog.show();
                break;
        }
    }

    private void setupData(List<Person> persons) {
        personList.clear();
        personList.addAll(persons);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_one:
                IDs = 0;
                break;
            case R.id.rb_two:
                IDs = 1;
                break;
        }
    }

    // 异步获取Excel数据信息
    private class ExcelDataLoader extends AsyncTask<String, Void, ArrayList<Person>> {
        @Override
        protected void onPreExecute() {
            progressDialog.setMessage("Excel数据导入中,请稍后......");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }

        @Override
        protected ArrayList<Person> doInBackground(String... params) {
            return getXlsData(params[0], 0);
        }

        @Override
        protected void onPostExecute(ArrayList<Person> persons) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            if (persons != null && persons.size() > 0) {
                // 列表显示数据
                setupData(persons);
            } else {
                // 加载失败
                Toast.makeText(MainActivity.this, "数据加载失败！", Toast.LENGTH_SHORT);
            }
        }
    }

    private class PersonAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        class TextViewHolder extends RecyclerView.ViewHolder {
            TextView tv_name, tv_number, tv_content;
            LinearLayout ll_index;

            public TextViewHolder(View itemView) {
                super(itemView);
                tv_name = (TextView) itemView.findViewById(R.id.tv_name);
                tv_number = (TextView) itemView.findViewById(R.id.tv_number);
                tv_content = (TextView) itemView.findViewById(R.id.tv_content);
                ll_index = (LinearLayout) itemView.findViewById(R.id.ll_index);
            }
        }

        @Override
        public TextViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new TextViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_person, parent, false));
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            if (holder instanceof TextViewHolder) {
                ((TextViewHolder) holder).tv_name.setText(personList.get(position).getUserName());
                ((TextViewHolder) holder).tv_number.setText(personList.get(position).getPhoneNumber());
                ((TextViewHolder) holder).tv_content.setText(personList.get(position).getMsgContent());
                ((TextViewHolder) holder).ll_index.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        phoneEt.setText(personList.get(position).getPhoneNumber());
                        contextEt.setText(personList.get(position).getMsgContent());
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return personList.size();
        }
    }


    public void asyMs(final String[] phonea, final String[] contexta, final int time) {
        new Thread() {

            public void run() {

                int temp = 0;
                for (String phone : phonea) {

                    Random ra = new Random();
                    int a = ra.nextInt(contexta.length);

                    temp++;

                    int sy = phonea.length - temp;


                    Random r = new Random();
                    int ab = r.nextInt(Data.a.length());

                    sendSms(IDs, phone, contexta[a] + Data.a.charAt(ab));
                    Log.e("nnnnnnnn", "" + Data.a.charAt(ab));
                    Message m = new Message();
                    m.obj = "还有" + sy + "个没有发，当前发送的号码是:" + phone + "发送的内容:\n" + contexta[a] + Data.a.charAt(ab);
                    hanStr.sendMessage(m);

                    try {
                        Thread.sleep(1000 * time);
                    } catch (InterruptedException e) {
                    }
                }
            }

        }.start();
    }


    public void asyMsg() {
        new Thread() {

            public void run() {

                while (true) {
                    try {
                        if (ConstData.phones.size() == 0 || ConstData.contest.size() == 0 || ConstData.workerTimeHash.getHuors() == null || ConstData.workerTimeHash.getMs() == null) {
                            continue;
                        }
                    } catch (Exception e) {
                        continue;
                    }

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    int i1 = calendar.get(Calendar.HOUR_OF_DAY);
                    String[] split = ConstData.workerTimeHash.getHuors().split(",");
                    boolean flag = false;
                    for (String s : split) {
                        int i = Integer.parseInt(s);
                        if (i == i1) {
                            flag = true;
                            break;
                        }
                    }

                    if (!flag) {
                        continue;
                    }


                    Random ra = new Random();
                    int a = ra.nextInt(ConstData.contest.size());
                    String message = null;

                    for (int i = 0; i < ConstData.contest.size(); i++) {
                        if (i == a) {
                            message = ConstData.contest.get(i);
                        }
                    }
                    if (message == null) {
                        message = ConstData.contest.pop();
                    }

                    Random r = new Random();
                    int ab = r.nextInt(Data.a.length());

                    try {
                        ConstData.open=true;
                        Integer total = ConstData.AUTH_DATA.getTotal();
                        if (total == null) {
                            ConstData.AUTH_DATA.setTotal(1);
                        } else {
                            ConstData.AUTH_DATA.setTotal(total + 1);
                        }
                        String pop = ConstData.phones.pop();
                        String s = message + Data.a.charAt(ab);
                        sendSms(IDs, pop, s);
                        Log.e("nnnnnnnn", "" + Data.a.charAt(ab));
                        Message m = new Message();
                        m.obj = "当前发送的号码是:" + pop + "发送的内容:\n" +s;
                        hanStr.sendMessage(m);
                        Thread.sleep(ConstData.workerTimeHash.getMs() * 1000);
                    } catch (Exception e) {
                    }
                }
            }

        }.start();
    }


    public void asyMsExcel(final List<Person> ps, final int time) {
        new Thread() {

            public void run() {

                int temp = 0;
                for (Person p : ps) {

                    temp++;

                    int sy = ps.size() - temp;
                    Random r = new Random();
                    int ab = r.nextInt(Data.a.length());

                    sendSms(IDs, p.getPhoneNumber(), p.getMsgContent() + Data.a.charAt(ab));

                    Message m = new Message();
                    m.obj = "还有" + sy + "个没有发，当前发送的号码是:" + p.getPhoneNumber() + "发送的内容:\n" + p.getMsgContent() + Data.a.charAt(ab);
                    hanStr.sendMessage(m);
                    try {
                        Thread.sleep(1000 * time);
                    } catch (InterruptedException e) {
                    }
                }
            }

        }.start();
    }


    Handler hanStr = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO: Implement this method
            String a = (String) msg.obj;
            Toast.makeText(getApplicationContext(), a, Toast.LENGTH_SHORT).show();


        }
    };


    // 获取本地Excel信息
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                Uri uri = data.getData();
                String path = uri.getPath().toString();
                tips.setText(path);

                // 执行Excel数据导入
                new ExcelDataLoader().execute(path.trim());
            }
        }
    }

    //@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    private void sendSms(final int which, String phone, String context) {


        String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

//创建接收返回的接收状态的Intent

        Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);

        PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);

        registerReceiver(new BroadcastReceiver() {

            @Override

            public void onReceive(Context _context, Intent _intent) {

                if (getResultCode() == Activity.RESULT_OK) {

                  if (ConstData.open){

                      Integer sent = ConstData.AUTH_DATA.getSent();
                      Log.e("----sent", "本来是：" + sent);
                      if (sent == null) {
                          ConstData.AUTH_DATA.setSent(1);
                      } else {
                          ConstData.AUTH_DATA.setSent(sent+1);
                      }
                      Toast.makeText(getApplication(), "发送成功", Toast.LENGTH_SHORT).show();
                      ConstData.open=false;
                  }

                } else {

                    if (ConstData.open){
                        Integer usent = ConstData.AUTH_DATA.getUnsent();
                        if (usent == null) {
                            ConstData.AUTH_DATA.setUnsent(1);
                        } else {
                            ConstData.AUTH_DATA.setUnsent(usent+1);
                        }
                        Toast.makeText(getApplication(), "发送失败，，，，", Toast.LENGTH_SHORT).show();
                        ConstData.open=false;
                    }

                }
            }

        }, new IntentFilter(DELIVERED_SMS_ACTION));


        SubscriptionInfo sInfo = null;

        final SubscriptionManager sManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);

        List<SubscriptionInfo> list = sManager.getActiveSubscriptionInfoList();

        if (list.size() == 2) {
            // 双卡
            sInfo = list.get(which);
        } else {
            // 单卡
            sInfo = list.get(0);
        }

        if (sInfo != null) {
            int subId = sInfo.getSubscriptionId();
            SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(subId);

            if (!TextUtils.isEmpty(phone)) {
                ArrayList<String> messageList = manager.divideMessage(context);
                for (String text : messageList) {
                    manager.sendTextMessage(phone, null, text, deliverPI, deliverPI);
                }


                Message m = new Message();
                m.obj = "信息正在发送，请稍候";
                hanStr.sendMessage(m);
            } else {


                Message m = new Message();
                m.obj = "无法正确的获取SIM卡信息，请稍候重试";
                hanStr.sendMessage(m);


            }
        }
    }
}
